package com.twg.demo.tcp;

import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetSocket;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class TcpClient {
    public static void main(String[] args) {
        new TcpClient().startConn();
    }

    private Vertx vertx;

    public void startConn(){
       vertx = Vertx.vertx();
       vertx.createNetClient().connect(8091,
               "127.0.0.1", new ClientConnHandle());
    }

    private class ClientConnHandle implements Handler<AsyncResult<NetSocket>> {
        @Override
        public void handle(AsyncResult<NetSocket> result) {
            if (result.succeeded()){
                NetSocket socket = result.result();

                socket.closeHandler(c -> {
                    log.info("connect to {} closed", socket.remoteAddress());
                    reconnect();
                });

                socket.exceptionHandler(e -> {
                   log.error("error exists", e);
                });

                byte[] req = "hello i am client".getBytes();
                int bodyLength = req.length;
                Buffer buffer = Buffer.buffer().appendInt(bodyLength).appendBytes(req);

                socket.write(buffer);
            }else {
                log.error("connect to server fail");
                reconnect();
            }
        }

        private void reconnect() {
            vertx.setTimer(1000*5 , res -> {
                log.info("try to reconnect to server");
                vertx.createNetClient().connect(8091,
                        "127.0.0.1", new ClientConnHandle());
            });
        }
    }
}
